package com.cheers.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.cheers.common.Constants;
import com.cheers.dao.IntegralDao;
import com.cheers.dao.UserDao;
import com.cheers.model.Integral;
import com.cheers.model.IntegralLog;
import com.cheers.model.User;
import com.cheers.service.IntegralService;

public class IntegralServiceImpl extends AbstractServiceImpl implements IntegralService {

	@Resource
	private IntegralDao integralDao;
	@Resource
	private UserDao userDao;

	@Override
	public List<Map<String, Object>> rank(int pageIndex, int pageSize)
			throws Exception {
		List<Map<String, Object>> result = null;
		List<Object[]> list = integralDao.rank(pageIndex*pageSize, pageSize);
		if (list!=null && !list.isEmpty()) {
			result = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = null;
			String userName = null;
			for (Object[] obj : list) {
				map = new HashMap<String, Object>();
				map.put("userId", obj[0]);
				userName = String.valueOf(obj[1]);
				if (userName.length() == 11) {
					userName = userName.substring(0, 6) + "*****";
				}
				map.put("userName", userName);
				map.put("point", obj[2]);
				result.add(map);
			}
		}
		return result;
	}

	@Override
	public Long getTotalPoint(String userId) throws Exception {
		return integralDao.getTotalPoint(userId);
	}
	
	@Override
	public String addPoint(String userId, String channel, int point)
			throws Exception {
		// 验证用户
		User user = userDao.get(User.class, userId);
		if (user == null) {
			return null;
		}

		// 积分累计记录
		IntegralLog integralLog = new IntegralLog();
		integralLog.setUserId(userId);
		integralLog.setChannel(channel);
		integralLog.setPoint(point);
		integralLog.setCtime(new Date());
		integralDao.save(integralLog);

		// 存储积分
		addIntegral(userId, channel, point);
		return Constants.OK;
	}

	@Override
	public void addIntegral(String userId, String channel, int point) throws Exception {
		Integral integral = integralDao.getIntegral(userId, channel);
		if (integral == null) {
			integral = new Integral();
			integral.setUserId(userId);
			integral.setChannel(channel);
		}
		if (Constants.CHANNEL_YOUMI.equals(channel) || Constants.DECREASE_LUCK.equals(channel) || Constants.DECREASE_BUY.equals(channel)) {
			//增量
			integral.setPoint(integral.getPoint()+point);
		} else if (Constants.CHANNEL_DIANLE.equals(channel)) {
			//全量
			integral.setPoint(point);
		}
		integralDao.save(integral);
		
		
//		Long result = null;
//		Jedis jedis = new Jedis(Constants.host, Constants.port);
//		jedis.connect();
//		jedis.auth(Constants.username + "-" + Constants.password + "-" + Constants.databaseName);
//		result = jedis.hincrBy(Constants.INTEGRAL_ALL, userId, point);
//		System.out.println(result);
//		return result;
	}

}
